package org.glxy.demo1.test;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileUpload {
    @PostMapping("/upload")
    public String upload(String nickname, MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        System.out.println("nickname = " + nickname);
        System.out.println("uploadFile = " + uploadFile.getOriginalFilename());
        System.out.println("uploadFile = " + uploadFile.getContentType());
        String path = request.getServletContext().getRealPath("/upload");
        saveFile(uploadFile,path);
        return "ok";
    }

    private void saveFile(MultipartFile uploadFile, String path) throws IOException {
        File uploadPath = new File(path);
        if (!uploadPath.exists()){
            uploadPath.mkdir();
        }
        File file = new File(path + "\\" + uploadFile.getOriginalFilename());
        uploadFile.transferTo(file);
    }
}
